import {Component, EventEmitter, forwardRef, Input, Output} from '@angular/core';
import {DialogProvider} from "@providers/dialog";
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms";
import {Events, Platform} from "ionic-angular";
import {AiProvider} from "@providers/natives/ai";

/**
 * Generated class for the SoundRecordComponent component.
 *
 * See https://angular.io/api/core/Component for more info on Angular
 * Components.
 */
@Component({
  selector: 'sound-record',
  templateUrl: 'sound-record.html',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => SoundRecordComponent),
    multi: true
  }],
})
export class SoundRecordComponent implements ControlValueAccessor {

  isApp: boolean;

  data: any;

  class: any;

  @Output() onRecording = new EventEmitter();

  @Input() show: boolean;
  private propagateChange = (_: any) => {
  };

  registerOnChange(fn: any): void {
    this.propagateChange = fn;
  }

  registerOnTouched(fn: any): void {
  }

  setDisabledState(isDisabled: boolean): void {
  }

  writeValue(value: any): void {
    this.data = value;
  }

  constructor(private dialog: DialogProvider,
              private ai: AiProvider,
              private events: Events,
              private platform: Platform) {
    this.platform.ready().then(() => {
      this.isApp = this.platform.is("cordova");
      console.log("platform:" + this.isApp);
    });
  }

  start() {
    this.onRecording.emit(true);
    if (this.isApp) {
      this.ai.start();
    }
  }

  stop() {
    if (this.isApp) {
      this.ai.stop();
    }
  }

  /**
   * 检测到用户开始说话
   */
  asrBegin() {
    this.dialog.showLoading()
  }

  /**
   * 语音识别结果
   */
  asrText(res) {
    let message = JSON.parse(res['message']);
    let str = message['best_result'];
    this.propagateChange(str);
  }

  /**
   * 语音识别功能完成
   */
  asrFinish() {
    this.dialog.hideLoading();
    this.onRecording.emit(false);
  }

  /**
   * 语音识别取消
   */
  asrCancel() {
    this.dialog.hideLoading();
    this.onRecording.emit(false);
  }

  ngOnInit() {
    this.events.subscribe('asrBegin', () => this.asrBegin());
    this.events.subscribe('asrText', (res) => this.asrText(res));
    this.events.subscribe('asrFinish', () => this.asrFinish());
    this.events.subscribe('asrCancel', () => this.asrCancel());
  }

  ngOnDestroy() {
    this.events.unsubscribe('asrBegin');
    this.events.unsubscribe('asrText');
    this.events.unsubscribe('asrFinish');
    this.events.unsubscribe('asrCancel');
  }
}
